#!/bin/env python

import sys, os
from Cheetah.Template import Template

class Result:
    def __init__(self, test, errors, expectedMean, expectedDeviation, actualMean, actualDeviation):
        self.test = test
        self.expectedMean = expectedMean
        self.expectedDeviation = expectedDeviation
        self.actualMean = actualMean
        self.actualDeviation = actualDeviation
        self.errors = errors
        self.passed = (errors==0 and ((expectedMean >= actualMean) and (expectedDeviation >= actualDeviation)))

    def __str__(self):
        return "test=%s passed=%s errors=%s expected[mean=%s deviation=%s] actual=[mean=%s deviation=%s]" % (self.test, self.passed, self.errors, self.expectedMean, self.expectedDeviation, self.actualMean, self.actualDeviation)

def getExpectations(folder):
    properties = open('src/performance-tests/%s/grinder.properties' % folder, 'r')
    expectationsList = [line.replace('\n', '').replace('\r', '') for line in properties.readlines() if line.startswith('expected')]
    expectations = {}
    for e in expectationsList:
        tokens = e.split('=')
        expectations[tokens[0]] = tokens[1]
    return expectations

def getActuals(folder):
    baseFolder = 'target/test-reports/performance/%s' % folder
    outFileName = [f for f in os.listdir(baseFolder) if f.startswith('out') and f.endswith('log')][0]
    out = open('%s/%s' % (baseFolder, outFileName), 'r')
    actualsLine = [line.replace('\n', '').replace('\r', '') for line in out.readlines() if line.startswith('Totals')][0]
    tokens = actualsLine.split()
    actuals = {}
    actuals['tests'] = tokens[1]
    actuals['errors'] = tokens[2]
    actuals['mean'] = tokens[3]
    actuals['deviation'] = tokens[4]
    actuals['tps'] = tokens[5]
    return actuals

def process(folder):
    expectations = getExpectations(folder)
    actuals = getActuals(folder)
    return getResult(folder, expectations, actuals)

def getResult(folder, expectations, actuals):
    expectedMean = float(expectations['expected.mean'])
    expectedDeviation = float(expectations['expected.deviation'])
    errors = int(actuals['errors'])
    actualMean = float(actuals['mean'])
    actualDeviation = float(actuals['deviation'])
    return Result(folder, errors, expectedMean, expectedDeviation, actualMean, actualDeviation)

def getTests():
    return os.listdir('target/test-reports/performance')

def generateReport(results):
    t = Template(file='src/tools/python/report.tmpl')
    t.results = results
    open('target/test-reports/performance/index.html', 'w').write(t.__str__())

if __name__ == "__main__":

    tests = getTests()
    results = []
    for test in tests:
        results.append(process(test))

    generateReport(results)

    failed = len([result for result in results if not result.passed])
    if failed>0:
        error ='%d tests failed' % failed
        raise Exception(error)

